package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import model.Reservation_Mesa;


public class Reservation_MesaDAO extends ModelDAO {

	private Connection connection;
		
	public Reservation_MesaDAO (){
		super();
		connection = getConnection();
	}
		
	public void closeConnection(){
		super.closeConnection();
	}
		
	public Reservation_Mesa select(int reservation_id,int mesa_id) {
		Reservation_Mesa rm = null;
		try{
			String consulta = "SELECT * FROM RESERVATIONS_MESAS WHERE MESA_ID=? AND RESERVATION_ID=?";
			PreparedStatement statement = this.connection.prepareStatement(consulta);
			
			try{statement.setInt(1, reservation_id);}
			catch(Exception e){e.printStackTrace();}
			
			try{statement.setInt(2, mesa_id);}
			catch(Exception e){e.printStackTrace();}
			
			ResultSet result = statement.executeQuery();
			rm = new Reservation_Mesa();
			while(result.next()){
				rm.setReservation_id(result.getInt(1));
				rm.setMesa_id(result.getInt(2));
			}
			result.close();
			statement.close();
		}
		catch(SQLException e){e.printStackTrace();}
		return rm;
	}
		
	public void create(Reservation_Mesa m){
		if(select(m.getReservation_id(),m.getMesa_id())!=null)return;
		
		try{
			String consulta = "INSERT INTO RESERVATIONS_MESAS "
				+"(RESERVATION_ID, MESA_ID)"
				+ " VALUES " + "(?,?)";
			PreparedStatement statement = this.connection.prepareStatement(consulta);
			
			try{statement.setInt(1, m.getReservation_id());}
			catch(Exception e){e.printStackTrace();}
			
			try{statement.setInt(2, m.getMesa_id());}
			catch(Exception e){e.printStackTrace();}
			
			statement.executeUpdate();
		    statement.close();
		}
		catch(SQLException e){e.printStackTrace();}	
	}
	
	public void delete(int id_rese, int id_mesa){
		try{
			String consulta = "DELETE FROM RESERVATIONS_MESAS WHERE RESERVATION_ID=?"+
				" AND MESA ID=?";
			PreparedStatement statement = this.connection.prepareStatement(consulta);
			statement.setInt(1,id_rese);
			statement.setInt(2,id_mesa);
			statement.executeUpdate(consulta);
			statement.close();
		}
		catch(SQLException e){e.printStackTrace();}
	}
}
